package com.ddw.meedeeuh.views;

import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.Frame;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;

import javax.swing.BorderFactory;
import javax.swing.JDialog;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JProgressBar;
import javax.swing.SwingUtilities;

import com.ddw.meedeeuh.presenters.MovieScraperPresenter.MovieScraperView;

@SuppressWarnings("serial")
public class MovieScraperViewImpl extends JDialog implements MovieScraperView {

	private final JProgressBar progressBar = new JProgressBar(JProgressBar.HORIZONTAL);
	private final JLabel statusLabel = new JLabel();

	public MovieScraperViewImpl(Component owner) {
		super((Frame)SwingUtilities.getRoot(owner));

		setTitle("Movie Scrape");
		setModalityType(ModalityType.APPLICATION_MODAL);

		final JPanel panel = (JPanel) getContentPane();
		panel.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));
		panel.add(this.statusLabel, BorderLayout.NORTH);
		panel.add(this.progressBar);

		setPreferredSize(new Dimension(400, 200));
		setDefaultCloseOperation(DO_NOTHING_ON_CLOSE);
	}

	@Override
	public Component asComponent() {
		return this;
	}

	@Override
	public void showView() {
		pack();
		setVisible(true);
	}

	@Override
	public void hideView() {
		setVisible(false);
	}

	@Override
	public void setProgress(final int percentage) {
		// Check we are in the right thread
		if(SwingUtilities.isEventDispatchThread() == false) {
			SwingUtilities.invokeLater(new Runnable() {

				@Override
				public void run() {
					setProgress(percentage);
				}
			});
			return;
		}

		this.progressBar.setValue(percentage);
	}

	@Override
	public void setMessage(final String message) {
		// Check we are in the right thread
		if(SwingUtilities.isEventDispatchThread() == false) {
			SwingUtilities.invokeLater(new Runnable() {

				@Override
				public void run() {
					setMessage(message);
				}
			});
			return;
		}

		this.statusLabel.setText(message);
	}

	@Override
	public void addCloseListener(final ActionListener listener) {
		addWindowListener(new WindowAdapter() {

			@Override
			public void windowClosing(WindowEvent e) {
				listener.actionPerformed(new ActionEvent(MovieScraperViewImpl.this, ActionEvent.ACTION_PERFORMED, null));
			}

		});
	}

	@Override
	public boolean validateClose() {
		return JOptionPane.showConfirmDialog(this,
				"Do you wish to cancel movie scraping?\nAny changes made so far will be saved.",
				"Scrape", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE) == JOptionPane.YES_OPTION;
	}

}
